import { Component, OnInit, ViewChild ,ChangeDetectorRef,} from '@angular/core';
import { ColumnType, SPage, TablePageComponent } from '@shared/components/table-page/table-page.component';
import { Body, _HttpClient } from '@delon/theme';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { AuthoEditComponent } from '../autho-edit/autho-edit.component';
import { ApiService } from '@core/services/api';
import { STData } from '@delon/abc';
import { reader }from '../../../../../assets/js/rdapi.js';
import { ACLService } from '@delon/acl';

@Component({
  selector: 'autho-list',
  templateUrl: './autho-list.component.html',
  styles: []
})
export class AuthoListComponent implements OnInit {
  @ViewChild('st', { static: false }) st: TablePageComponent;
  readFlag:boolean = this.aclService.canAbility("autho-list/read");//检查用户按钮权限
  selectData: any[];
  loading = false;
  showTable=false;
  addUserInfo = {
    userAccount: '',
    userPassword: '',
    userName: '',
    roles: [],
    depts: []
  };
  g_device:string="00";
  g_isOpen:boolean= false;
  g_wantFunc:number=0;
  cardNo:string;
  config: SPage = {
    columns: [
      {
        index: 'id',
        title: '多选',
        type: ColumnType.checkbox,
        filter: {
          items:[],
          index:'areaId',
          placeholder: '请输入小区名称',
          type: 'select',
        }
      },
      {
        index: 'cardNo',
        title: '卡号',
        width:100,
        fFn: (item, columu) => this.delCardZero(item.cardNo),
        filter: {
          index:'houseName',
          placeholder: '请输入地址',
          type: 'string'
        }
      },
      {
        index: 'cardCode',
        title: '卡编号',
        width:100,
        filter: {
          placeholder: '请输入卡编号',
          type: 'string'
        }
      },
      {
        index: 'cardType',
        title: '卡类型',
        type: ColumnType.tag,
        tag: {
          1:{text:'IC卡'},
          2:{text:'CPU卡'},
          3:{text:'身份证'},
          4:{text:'居住证'},
          5:{text:'银行卡'},
          6:{text:'APP'},
        },
        filter: {
          index:'startTime',
          placeholder: '到期时间(起)',
          type: 'date'
        }
      },
      {
        index: 'cardCategory',
        title: '卡属性',
        type: ColumnType.tag,
        tag:{
          1:{text:'房东卡'},
          2:{text:'租户卡'},
        },
      },
      {
        index: 'cardStatus',
        title: '状态',
        type: ColumnType.tag,
        tag:{
          0:{text:'未激活',color: 'red'},
          1:{text:'已激活', color: 'green'},
          2:{text:'丢失', color: 'red'},
          3:{text:'损坏', color: 'red'},
          4:{text:'冻结', color: 'red'},
          5:{text:'待缴费', color: 'red'},
          6:{text:'已过期', color: 'red'},
          7:{text:'退卡', color: 'red'},
          9:{text:'其他'}
        },
        filter: {
          index:'endTime',
          placeholder: '到期时间(止)',
          type: 'date'
        }
      },
      {
        index: 'infoName',
        title: '持卡人',
        filter: {
          index:'cardNo',
          placeholder: '卡号',
          type: 'string',
          defatuts:"",
        }
      },
      {
        index: 'infoMobile',
        title: '持卡人手机号',
        filter: {
          index:'infoName',
          placeholder: '持卡人',
          type: 'string'
        }
      },
      {
        index: 'houseName',
        title: '详细地址',
      },
      {
        index: 'cardUsingEndTime',
        title: '到期时间',
        width:150
      },
      {
        index: 'infoMobile',
        title: '注销时间',
        filter: {
          index:'cardCategory',
          placeholder: '居住类别',
          type: 'select',
          items: [
            {label: '房东', value: 1},
            {label: '租户', value: 2},
          ]
        }
      },
      {
        index:"createBy",
        title:"创建人"
      },
      {
        index:'createTime',
        title:'创建时间',
        width:150
      },
      {
        index: '',
        title: '操作',
        width:150,
        fixed:'right',
        buttons:[
          {
            text:'门禁权限',
            click:(_record)=>{
              this.editDic(_record);
            }
          }
        ]
      },
   
    ],
    showCheckBox: true,
    reqUrl:this.api.doorCard.queryPeopleCardInfo.url,
    // editBtn: [
    //   // { title: '审批' }
    //   {title : '门禁权限'}
    // ]
  }
  constructor(private http: _HttpClient,  private api: ApiService, private modal: NzModalService, private message: NzMessageService,private aclService: ACLService, private ref: ChangeDetectorRef,) { }
  
    //删除卡号后面的8个0
    delCardZero(num:string):string{
      if(num.length > 8){
        num = num.substring(0,num.length - 8);
      }
      return num;
    }
 
   //获取小区下拉框数据
   feachCommunity(){
     this.http.post(this.api.area.list.url, {areaName: ''}).subscribe((res: any) => {
      if (res.status == '200') {
        this.config.columns[0].filter.items= res.data.map(item => {
          return {
            label: item.areaName,
            value: item.id
          }
        });
        this.showTable=true;
      }
    })
  }

  // 编辑功能开始
  editDic(_param?: object): void {
    const modal = this.modal.create({
      nzTitle: '门禁权限',
      nzContent: AuthoEditComponent,
      nzWidth: 1200,
      nzComponentParams: {
        _param
      },
      nzOnOk: () => {
        // this.st.reload();
      },
      nzFooter: null
    })
    modal.afterClose.subscribe(res => {
      if (res === 'ok') {
        // this.st.reload();
      }
    })
  }
  
  operate(e: any): void {
    if (e.title === '审批') {
      this.editDic(e.data);
    }
  }
  _console(e: any): void {
    this.selectData = e;
  }

  dataProcess(data: STData[]){
    console.log(data);
    return data;
  }

  ngOnInit() {
    this.feachCommunity();
    if(reader.SocketOpen){
      this.Connect();
    }else{
      reader.createSocket();
      setTimeout(()=>{
        this.Connect();
      },200)
    }
    reader.onResult((rData:any)=>{
      switch(rData.strCmdCode){
        case "0007":
          if(rData.strStatus != "00"){
            this.message.error("连接设备失败!");
          }else{
            this.g_isOpen=true;
            console.log("连接成功")
          }
          break;
        case "1001":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
             case 1:
              reader.send(this.g_device + "1002"); //TyA_Anticollision
              break;
          }
          break;
        case "1002":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
              case 1 :
                this.showTable=false;
                //console.log(rData.strData);
                this.config.columns[6].filter.defatuts=rData.strData;
                this.ref.detectChanges();
                this.showTable=true;
              break;
          }
          break;
      }
     
    })
  }

  ngOnDestroy(){
    reader.Disconnect();
  }

  //读卡
  readCard(){
    if(this.g_isOpen != true){
      this.message.error("请连接读卡器!");
      return;
    }
    
    //Start read UID
    reader.send(this.g_device + "1001" + "52"); //TyA_Request
    this.g_wantFunc = 1;  
    reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
  }

  //连接读卡器
Connect(){
	reader.send(this.g_device + "0007" + "00"); //Open the USB device with index number 0. (打开索引号为0的USB设备)
	reader.send(this.g_device + "0109" + "41"); //Set to ISO14443a working mode. (设置为ISO14443A工作模式)
	reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)
 this.LedGreen();
 let that=this;
  setTimeout(function(){that.LedRed()},200); 
  reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
}

LedGreen(){
 reader.send(this.g_device + "0107" + "02"); 
}

LedRed(){
  reader.send(this.g_device + "0107" + "01"); 
}
}
